<template>
  <div class="global-header">
    <div class="header-container">
      <!-- 左侧：Logo和标题 -->
      <div class="header-left">
        <RouterLink to="/" class="logo-link">
          <img class="logo" src="@/assets/logo.png" alt="Logo" />
          <h1 class="site-title">Code Studio</h1>
        </RouterLink>
      </div>

      <!-- 中间：导航菜单 -->
      <div class="header-center">
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="horizontal"
          :items="filteredItems"
          class="nav-menu"
          @click="handleMenuClick"
        />
      </div>

      <!-- 右侧：用户操作区域 -->
      <div class="header-right">
        <div v-if="userStore.loginUser.id" style="color: rgba(255, 255, 255, 0.9)">
          欢迎您：&nbsp;<b>{{ userStore.loginUser.userName ?? '无名' }}</b
        >&nbsp;&nbsp;&nbsp;&nbsp;
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              <a-avatar :size="40" :src="userStore.loginUser.userAvatar">
                <template #icon><UserOutlined /></template>
              </a-avatar>
            </a>
            <template v-slot:overlay>
              <a-menu>
                <a-menu-item>
                  <UserOutlined class="input-icon" />
                  <RouterLink to="/user/info">个人信息</RouterLink>
                </a-menu-item>
                <a-menu-item>
                  <LockOutlined class="input-icon"/>
                  <RouterLink to="/user/pwd">修改密码</RouterLink>
                </a-menu-item>
                <a-menu-item>
                  <LogoutOutlined class="input-icon" />
                  <a @click="userLoginOut">退出登录</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          <a-button type="primary" class="login-btn" @click="showUserLoginPage">
            登录
          </a-button>
        </div>
      </div>
    </div>

    <!-- 登录弹窗 -->
    <userLoginPage
      v-model:open="userLoginPageVisible"
      @login-success="handleLoginSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { h, ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { type MenuProps, message } from 'ant-design-vue'
import userLoginPage from '../pages/user/UserLoginPage.vue'

import {
  LockOutlined,
  LogoutOutlined,
  HomeOutlined,
  SaveOutlined,
  ReloadOutlined, UserOutlined
} from '@ant-design/icons-vue'

const router = useRouter()
const route = useRoute()

import { useLoginUserStore } from '@/stores/user'
import { userLogout } from '@/api/userController.ts'

const userStore = useLoginUserStore()

/**
 * 用户退出登录
 */
const userLoginOut = async () => {
  const res = await userLogout()
  if (res.data.code === 0) {
    message.success('退出成功', 2)
    userStore.setLoginUser({
      userName: '未登录',
    })
    // 重定向到登录页
    userLoginPageVisible.value = true
  } else {
    message.error('退出失败')
  }
}

// 当前选中菜单
const selectedKeys = ref<string[]>(['/'])

// 登录弹窗状态
const userLoginPageVisible = ref(false)

// 菜单配置项
const originItems = ref([
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '首页',
    title: '首页',
  },
  {
    key: '/about',
    label: '关于',
    title: '关于我们',
  },
  {
    key: '/admin/userManage',
    label: '用户管理',
    title: '用户管理',
  },
  {
    key: 'external',
    label: h('a', {
      href: 'https://www.codefather.cn',
      target: '_blank',
      style: { color: 'rgba(255, 255, 255, 0.85)' }
    }, '编程导航'),
    title: '编程导航',
  },
])

// 过滤菜单项 - 基于用户角色权限
const filteredItems = computed(() => {
  return originItems.value.filter(item => {
    // 如果菜单项的 key 以 /admin 开头，需要检查用户权限
    if (item.key.startsWith('/admin')) {
      // 只有当用户角色是 admin 时才显示管理员菜单
      return userStore.loginUser.userRole === 'admin'
    }
    // 其他菜单项正常显示
    return true
  })
})

// 初始化选中菜单
onMounted(() => {
  selectedKeys.value = [route.path]
})

// 监听路由变化，更新当前选中菜单
router.afterEach((to) => {
  selectedKeys.value = [to.path]
})

// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = (e) => {
  const key = e.key as string

  // 如果是外部链接，不处理路由跳转
  if (key === 'external') {
    return
  }

  selectedKeys.value = [key]

  // 跳转到对应页面
  if (key.startsWith('/')) {
    router.push(key)
  }
}

// 显示登录弹窗
const showUserLoginPage = () => {
  userLoginPageVisible.value = true
}

// 处理登录成功
const handleLoginSuccess = async (data: any) => {
  await userStore.fetchLoginUser()
  await router.push({
    path: '/',
    replace: true,
  })
}
</script>

<style scoped>
.input-icon {
  padding-right: 8px;
  color: #667eea;
}

.global-header {
  height: 64px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
  position: relative;
  overflow: hidden;
}

.global-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.9) 0%, rgba(118, 75, 162, 0.9) 100%);
  backdrop-filter: blur(10px);
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  position: relative;
  z-index: 1;
}

.header-left {
  flex-shrink: 0;
}

.logo-link {
  display: flex;
  align-items: center;
  gap: 12px;
  text-decoration: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 8px 12px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.logo-link:hover {
  transform: translateY(-2px) scale(1.02);
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.logo {
  height: 40px;
  width: 40px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.logo-link:hover .logo {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
  transform: rotate(5deg);
}

.site-title {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #ffffff;
  letter-spacing: 0.5px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
  max-width: 600px;
  margin: 0 40px;
}

.header-right {
  flex-shrink: 0;
}

.login-btn {
  height: 40px;
  border-radius: 20px;
  font-weight: 600;
  padding: 0 24px;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  border: none;
  color: white;
  box-shadow: 0 4px 15px rgba(238, 90, 36, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.login-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s;
}

.login-btn:hover::before {
  left: 100%;
}

.login-btn:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 25px rgba(238, 90, 36, 0.6);
  background: linear-gradient(135deg, #ff7675 0%, #fd79a8 100%);
}

/* 菜单样式覆盖 */
:deep(.nav-menu) {
  background: transparent !important;
  border-bottom: none !important;
  line-height: 64px !important;
}

:deep(.nav-menu .ant-menu-item) {
  color: rgba(255, 255, 255, 0.9) !important;
  border-bottom: 2px solid transparent !important;
  margin: 0 4px !important;
  padding: 0 20px !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  border-radius: 8px 8px 0 0 !important;
  font-weight: 500 !important;
  position: relative !important;
  overflow: hidden !important;
}

:deep(.nav-menu .ant-menu-item::before) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.1);
  transform: translateY(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.nav-menu .ant-menu-item:hover::before) {
  transform: translateY(0);
}

:deep(.nav-menu .ant-menu-item:hover) {
  color: #ffffff !important;
  border-bottom-color: #ff6b6b !important;
  background: transparent !important;
  transform: translateY(-2px) !important;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3) !important;
}

:deep(.nav-menu .ant-menu-item-selected) {
  color: #ffffff !important;
  border-bottom-color: #ff6b6b !important;
  background: rgba(255, 107, 107, 0.2) !important;
  font-weight: 600 !important;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3) !important;
}

:deep(.nav-menu .ant-menu-item-selected::after) {
  border-bottom-color: #ff6b6b !important;
  height: 3px !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 16px;
  }

  .header-center {
    margin: 0 20px;
  }

  .site-title {
    font-size: 18px;
  }

  :deep(.nav-menu .ant-menu-item) {
    margin: 0 4px !important;
    padding: 0 12px !important;
  }
}

@media (max-width: 480px) {
  .header-container {
    padding: 0 12px;
  }

  .header-center {
    margin: 0 12px;
  }

  .site-title {
    display: none;
  }

  .logo {
    height: 36px;
    width: 36px;
  }

  :deep(.nav-menu .ant-menu-item) {
    margin: 0 2px !important;
    padding: 0 8px !important;
    font-size: 14px !important;
  }

  .login-btn {
    height: 32px;
    font-size: 14px;
  }
}
</style>
